import { CONFIG } from '@/envs/_/config'
import {
  HOST,
  API_STATUS,
  API_RESPONSE_CODE
} from '../constant'
const cache = {}

uni.addInterceptor('request', {
  invoke(args) {
    const url = `${HOST.BASE_URL}${args.url}`
    args.url = url
    args.data = args.data || {}
    args.data.appId = CONFIG.WX_APPID
    args.data.company_id = CONFIG.COMPANY_ID
    if (cache.token) {
      args.data.token = cache.token
    }
    console.log(`--------request start: ${url}, params: ${JSON.stringify(args.data)}--------`)
    if (!args.noLoading) {
      uni.showLoading()
    }
  },
  success(result) {
    uni.hideLoading()
    result.data.success = false
    if (result.data.res === API_STATUS.SUCCESS
     || (result.data.res !== API_STATUS.FAIL && result.errMsg === 'request:ok')
     || result.data.errcode === API_RESPONSE_CODE.SUCCESS) {
      result.data.success = true
      console.log(`-------request success: ${JSON.stringify(result)}-------`)
      if (result.data.token) {
        cache.token = result.data.token
      }
    } else if (result.data.code === API_RESPONSE_CODE.NOT_LOGIN) {
      uni.redirectTo({
        url: '/pages/entrance/login/login'
      })
    } else {
      console.error(`-------request fail: ${JSON.stringify(result.data)}-------`)
      uni.showToast({
        title: result.data.message || '获取数据失败',
        icon: 'none',
        duration: 2000
      })
    }
  },
  fail(err) {
    uni.hideLoading()
    console.error(`-------request fail: ${JSON.stringify(err)}-------`)
    const ignoreCase = ['request:fail abort', 'request:fail timeout']
    if (!ignoreCase.includes(err?.errMsg)) {
      uni.showToast({
        title: '获取数据失败',
        icon: 'none',
        duration: 2000
      });
    }
  }
})

uni.addInterceptor('uploadFile', {
  invoke(args) {
    const url = `${HOST.BASE_URL}${args.url}${cache.token ? `?token=${cache.token}` : ''}`
    args.url = url
    console.log(`--------upload start: ${url}, name: ${args.name}, path: ${args.filePath}--------`)
    uni.showLoading()
  },
  success(result) {
    uni.hideLoading()
    if (typeof result.data === 'string') {
      try {
        result.data = JSON.parse(result.data)
      } catch (e) {
        console.error('upload 解析JSON失败')
      }
    }
    if (result.data.res === API_STATUS.SUCCESS) {
      console.log(`-------upload success: ${JSON.stringify(result)}-------`)
    } else {
      console.error(`-------upload fail: ${JSON.stringify(result.data)}-------`)
      uni.showToast({
        title: result.data.message || '操作失败',
        icon: 'none',
        duration: 2000
      })
    }
  },
  fail(err) {
    uni.hideLoading()
    console.error(`-------upload fail: ${JSON.stringify(err)}-------`)
    uni.showToast({
      title: '操作失败',
      icon: 'none',
      duration: 2000
    })
  }
})
